package com.thesis.controller;

import com.thesis.common.*;
import com.thesis.entity.*;
import com.thesis.service.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Anvy at 2020/4/19.
 */
@Controller
@RequestMapping({"/user"})
public class UserController {
    
    private static  final Logger logger= LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;


    @Value("${com.jane.security.md5.key}")
    private String md5Key;

    @Value("${com.jane.file.baseFilePath}")
    private String baseFilePath;


    @RequestMapping("/checkLogin")
    @ResponseBody
    public ResponseBean checkLogin(SysUser user, HttpSession session, @RequestParam String verifyCode) {
        //首先验证验证码是否存在
        String trueVerifyCode = (String) session.getAttribute("verifyCode");
        if (trueVerifyCode == null) {
            return new ResponseBean(false, CommonEnum.REFRESH_VERIFYCODE);
        }
        String mobile = user.getMobile();
        String password = user.getPassword();
        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
            logger.debug("手机号或密码为空！");
            return new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        //判断验证码是否输入正确（验证码忽略大小写）
        if (!trueVerifyCode.equalsIgnoreCase(verifyCode)) {
            return new ResponseBean(false, CommonEnum.ERROR_VERIFYCODE);
        }
        //根据手机号查找用户
        SysUser userByMobile = userService.findByMobile(mobile);
        if(userByMobile==null){
            return new ResponseBean(false,CommonEnum.NO_USER_EXIST);
        }
        //判断密码是否正确
        if (!MD5Util.md5Verify(user.getPassword(), this.md5Key, userByMobile.getPassword())) {
            return new ResponseBean(false, CommonEnum.INVALID_PASSWORD);
        }
        //通过所有验证
        session.setAttribute("user", userByMobile);
        session.setAttribute("type", userByMobile.getType());
        return new ResponseBean<>(true, "登录成功！", CommonEnum.LOGIN_SUCCESS);
    }

    @RequestMapping("registPage")
    public String registPage(Model model){
        return "regist";
    }

    @RequestMapping("addPage")
    public String addPage(Model model){
        return "user/add";
    }



    //添加代收员页面
    @RequestMapping("addReceiverPage")
    public String addReceiverPage(Model model){
        return "receiver/add";
    }
    //添加回收员页面
    @RequestMapping("addCollectorPage")
    public String addCollectorPage(Model model){
        return "collector/add";
    }

    @RequestMapping("add")
    @ResponseBody
    public ResponseBean addUser(@RequestBody SysUser user, MultipartFile file){
        logger.debug("addSysUser:"+user);
        if(user==null){
            return  new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        String mobile = user.getMobile();
        if(StringUtils.isEmpty(mobile)){
            logger.error("手机号为空！");
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        String userCode = user.getCode();
//        if(StringUtils.isEmpty(userCode)){
//            logger.debug("编码为空！");
//            return new ResponseBean(false,CommonEnum.BAD_REQUEST);
//        }
        if(!StringUtils.isEmpty(userCode)){
            SysUser checkCodeUser=new SysUser();
            checkCodeUser.setCode(userCode);
            Page<SysUser> userCodeList = userService.findPageList(checkCodeUser);
            if(userCodeList!=null&&userCodeList.size()>0){
                return  new ResponseBean(false,"编码已经存在！");
            }
        }

        //检测手机号是否已经存在
        SysUser checkUser=new SysUser();
        checkUser.setMobile(mobile);
        Page<SysUser> pageUserList = userService.findPageList(checkUser);
        if(pageUserList!=null&&pageUserList.size()>0){
            return new ResponseBean(false,"9999","手机号已经存在！");
        }
        String password=StringUtils.isEmpty(user.getPassword())?"123456":user.getPassword();
        user.setPassword(MD5Util.md5(password,md5Key));
        Integer add = userService.insertSelective(user);
        logger.debug("用户添加结果："+user);
        //保存文件并更新saveName到user.field1
        if (file!=null&&!file.isEmpty()) {
            SysFile sysFile=new SysFile();
            sysFile.setObjectId(user.getId());
            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
                user.setField1(saveFile.getSaveName());
            }
            userService.updateByPrimaryKeySelective(user);
        }
        return new ResponseBean<>(true, user, CommonEnum.SUCCESS_REQUEST);
    }

    /**
     * 跳转到用户修改页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/editPage/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.selectByPrimaryKey(id));
        return "user/edit";
    }
    //编辑代收员页面
    @RequestMapping("/editReceiverPage/{id}")
    public String editReceiverPage(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.selectByPrimaryKey(id));
        return "receiver/edit";
    }
    //编辑回收员页面
    @RequestMapping("/editCollectorPage/{id}")
    public String editCollectorPage(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.selectByPrimaryKey(id));
        return "collector/edit";
    }

    @RequestMapping("initPwd")
    @ResponseBody
    public ResponseBean initPwd(Long id){
        if(id==null||id<1){
            return new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        SysUser sysUser = userService.selectByPrimaryKey(id);
        if(sysUser!=null){
            sysUser.setPassword(MD5Util.md5("123456",md5Key));
            sysUser.setUpdateTime(new Date());
            userService.updateByPrimaryKeySelective(sysUser);
            return new ResponseBean(true, CommonEnum.SUCCESS_OPTION);
        }
        return new ResponseBean(false, CommonEnum.NO_USER_EXIST);
    }

    /**
     * 用户修改
     * @param user
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseBean updateById(MultipartFile file, SysUser user) {
        if (user == null) {
            return new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        String mobile = user.getMobile();
        if(StringUtils.isEmpty(mobile)){
            return new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        //检测手机号是否已经存在
        SysUser checkUser=new SysUser();
        checkUser.setMobile(mobile);
        checkUser.setId(user.getId());
        List<SysUser> sysUsers = userService.checkObj(checkUser);
        if(sysUsers!=null&&sysUsers.size()>0){
            return new ResponseBean(false,"9999","手机号已经存在！");
        }
        checkUser.setMobile(null);
        if(!StringUtils.isEmpty(user.getCode())){
            checkUser.setCode(user.getCode());
            sysUsers=userService.checkObj(checkUser);
            if(sysUsers!=null&&sysUsers.size()>0){
                return new ResponseBean(false,"9999","编码已经存在！");
            }
        }

        String password = user.getPassword();
        if(!StringUtils.isEmpty(password)){
            user.setPassword(MD5Util.md5(password,md5Key));
        }
        if (file!=null&&!file.isEmpty()) {
            SysFile sysFile=new SysFile();
            sysFile.setObjectId(user.getId());
            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
                user.setField1(saveFile.getSaveName());
            }
        }
        user.setUpdateTime(new Date());
        int i = userService.updateByPrimaryKeySelective(user);
        return new ResponseBean(true, CommonEnum.SUCCESS_OPTION);
    }

    /**
     * 跳转列表页面
     * @return
     */
    @RequestMapping("/listPage")
    public String userListPage(Model model) {
        return "user/list";

    }
    //跳到代收员列表页面
    @RequestMapping("/receiverListPage")
    public String teacherListPage(Model model) {
        return "receiver/list";

    }
    //跳到回收员列表页面
    @RequestMapping("/collectorListPage")
    public String collectorListPage(Model model) {
        return "collector/list";
    }

    /**
     * 获取回收员列表
     * @param pageNum
     * @param pageSize
     * @param queryParam
     * @param vagueParam
     * @param request
     * @return
     */
    @RequestMapping("/collectorList/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean collectorList(@PathVariable Integer pageNum,@PathVariable Integer pageSize,
                                SysUser queryParam,String vagueParam,HttpServletRequest request) {
        Object type = request.getSession().getAttribute("type");
        if(type.toString().equals("2")){
            //回收员登录，则只能维护自己信息
            SysUser sysUser= (SysUser) request.getSession().getAttribute("user");
            queryParam.setId(sysUser.getId());
        }
        queryParam.setType(2);
        logger.debug("查询列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        PageHelper.startPage(pageNum, pageSize);
        Page<SysUser> pageListByVague = userService.findPageListByVague(queryParam, vagueParam);
        logger.debug("获取的列表："+pageListByVague);
        //获取分页信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", pageListByVague.getPageSize());
        pageInfo.put("pageNum", pageListByVague.getPageNum());
        pageInfo.put("pages", pageListByVague.getPages());
        pageInfo.put("total", pageListByVague.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userList", pageListByVague);
        resultMap.put("pageInfo", pageInfo);
        return new ResponseBean<Map<String, Object>>(true, resultMap, CommonEnum.SUCCESS_REQUEST);
    }
    /**
     * 获取代收员列表
     * @param pageNum
     * @param pageSize
     * @param queryParam
     * @param vagueParam
     * @param request
     * @return
     */
    @RequestMapping("/receiverList/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean teacherList(@PathVariable Integer pageNum,@PathVariable Integer pageSize,
                                SysUser queryParam,String vagueParam,HttpServletRequest request) {
        Object type = request.getSession().getAttribute("type");
        if(type.toString().equals("1")){
            //代收员登录，则只能维护自己信息
            SysUser sysUser= (SysUser) request.getSession().getAttribute("user");
            queryParam.setId(sysUser.getId());
        }
        queryParam.setType(1);
        logger.debug("查询列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        PageHelper.startPage(pageNum, pageSize);
        Page<SysUser> pageListByVague = userService.findPageListByVague(queryParam, vagueParam);
        logger.debug("获取的列表："+pageListByVague);
        //获取分页信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", pageListByVague.getPageSize());
        pageInfo.put("pageNum", pageListByVague.getPageNum());
        pageInfo.put("pages", pageListByVague.getPages());
        pageInfo.put("total", pageListByVague.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userList", pageListByVague);
        resultMap.put("pageInfo", pageInfo);
        return new ResponseBean<Map<String, Object>>(true, resultMap, CommonEnum.SUCCESS_REQUEST);
    }

    /**
     * 分页列表查询
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param queryParam 查询参数
     * @param vagueParam 模糊参数
     * @return
     */
    @RequestMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean getList(@PathVariable Integer pageNum,@PathVariable Integer pageSize,
                                SysUser queryParam,String vagueParam,HttpServletRequest request) {
        Object user = request.getSession().getAttribute("user");
        Object type = request.getSession().getAttribute("type");

        if(user!=null&&type.toString().equals("0")){
            SysUser loginUser= (SysUser) user;
            queryParam.setId(loginUser.getId());
        }
        queryParam.setType(0);
        logger.debug("查询用户列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        PageHelper.startPage(pageNum, pageSize);
        Page<SysUser> pageListByVague = userService.findPageListByVague(queryParam, vagueParam);
        logger.debug("获取的用户列表："+pageListByVague);
        //获取分页信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", pageListByVague.getPageSize());
        pageInfo.put("pageNum", pageListByVague.getPageNum());
        pageInfo.put("pages", pageListByVague.getPages());
        pageInfo.put("total", pageListByVague.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userList", pageListByVague);
        resultMap.put("pageInfo", pageInfo);
        return new ResponseBean<Map<String, Object>>(true, resultMap, CommonEnum.SUCCESS_REQUEST);
    }
    /**
     * 分页列表查询
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param queryParam 查询参数
     * @param vagueParam 模糊参数
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseBean getWxList( Integer pageNum, Integer pageSize,
                                SysUser queryParam,String vagueParam) {
        logger.debug("查询用户列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        PageHelper.startPage(pageNum, pageSize);
        Page<SysUser> pageListByVague = userService.findPageListByVague(queryParam, vagueParam);
        logger.debug("获取的用户列表："+pageListByVague);
        //获取分页信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", pageListByVague.getPageSize());
        pageInfo.put("pageNum", pageListByVague.getPageNum());
        pageInfo.put("pages", pageListByVague.getPages());
        pageInfo.put("total", pageListByVague.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userList", pageListByVague);
        resultMap.put("pageInfo", pageInfo);
        return new ResponseBean<Map<String, Object>>(true, resultMap, CommonEnum.SUCCESS_REQUEST);
    }

    @RequestMapping("deleteBatchByIds")
    @ResponseBody
    public ResponseBean deleteBatchByIds(@RequestParam List<Integer> idList){
        logger.debug("deleteBatchByIds:"+idList);
        if(idList==null||idList.isEmpty()){
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        Integer delete = userService.deleteBatchByIds(idList);
        logger.debug("批量删除结果："+delete);
        return new ResponseBean<Map<String, Object>>(true, null, CommonEnum.SUCCESS_REQUEST);
    }
    @RequestMapping("deleteById")
    @ResponseBody
    public ResponseBean deleteById(@RequestParam Long id){
        logger.debug("deleteById:"+id);
        if(id==null||id<0){
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        Integer delete = userService.deleteByPrimaryKey(id);
        logger.debug("删除结果："+delete);
        return new ResponseBean<Map<String, Object>>(true, null, CommonEnum.SUCCESS_REQUEST);
    }

}
